package com.fs.controller.v1;

import com.fs.controller.vo.PageData;
import com.fs.controller.vo.price.ReqCreateRoomPrice;
import com.fs.controller.vo.price.ReqGetPrice;
import com.fs.controller.vo.price.RespRoomPrice;
import com.fs.global.init.RoleName;
import com.fs.service.PriceService;
import com.fs.service.bo.BoPageInfo;
import com.fs.service.bo.price.BoCreateRoomPriceParam;
import com.fs.service.bo.price.BoPrice;
import com.fs.service.bo.price.BoPriceWithRoom;
import com.fs.service.bo.price.BoQueryParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "房间价格管理", description = "管理员账户使用")
@RestController
@RequestMapping("/v1/price")
@RequiresRoles(RoleName.ADMIN)
@Validated
public class PriceController {
    private final PriceService priceService;


    public PriceController(PriceService priceService) {
        this.priceService = priceService;
    }

    //创建房间价格
    @ApiOperation("创建房价价格")
    @PostMapping
    public RespRoomPrice CreateRoomPrice(@RequestBody @Valid ReqCreateRoomPrice req) {
        List<BoPrice> pricesOfRoom = priceService.getPricesOfRoom(req.getRoomId());
        LocalTime beginDateTime = LocalTime.parse(req.getBeginDateTime());
        LocalTime endDateTime = LocalTime.parse(req.getEndDateTime());
        if (endDateTime.isBefore(beginDateTime)) {
            throw new BadRequestException("时间参数异常");
        }

        boolean right = pricesOfRoom.stream().allMatch(
                p -> beginDateTime.isAfter(p.getEndTime()) || beginDateTime.equals(p.getEndTime())
                        || endDateTime.isBefore(p.getBeginTime()) || endDateTime.equals(p.getBeginTime())
        );

        if (!right) {
            throw new BadRequestException("该时间段有重复的数据");
        }
        BoCreateRoomPriceParam param = new BoCreateRoomPriceParam().setEndTime(endDateTime).setBeginTime(beginDateTime).setPrice(req.getPrice()).setRoomId(req.getRoomId());
        BoPriceWithRoom price = priceService.createPrice(param);
        return new RespRoomPrice(price);
    }

    @ApiOperation("删除房价价格")
    @DeleteMapping("{priceId}")
    public void deleteRoomPrice(@PathVariable("priceId") Integer priceId) {
        priceService.deletePrice(priceId);
    }



}
